-module(l2_packet_fun).
-include("protocol.hrl").
-export[do/2,do/1,parse/1,start/0,start_link/0].

-define(SERVER,?MODULE).

-record(l2_counter,{
		packet_counter = 0,
		unicast_counter = 0,
		ip_counter = 0,
		unknown_counter = 0
		}).
start() ->
	parser_eng:start(fun do/2).
	
start_link() ->
	parser_eng:start_link(fun do/2).

parse(Packet_Tuple) ->
	gen_server:cast(?SERVER,{packet_comming,Packet_Tuple}).
	
do(stop) ->
	gen_server:call(?SERVER,stop);
do(report) ->
	Counter = gen_server:call(?SERVER,report),
	io:format("L2 Counter ~n ~p ~n",[Counter]);
do(reset_counter) ->
	gen_server:call(?SERVER,reset_counter).
	

do(init,_) ->
	#l2_counter{};	
do(get,protocol_id) ->
	?SERVER;
do(report,State) ->
	State;
do(reset,State) ->
	#l2_counter{};
do(packet_comming,{P_Tuple,Counter}) ->
	case P_Tuple#packet_tuple.packet of
	<<S_MAC:48,D_MAC:48,16#0800:16,IP_Packet/bytes>> ->
		packet_dispatch:do(ip_packet,P_Tuple#packet_tuple{packet=IP_Packet,size = P_Tuple#packet_tuple.size - 14,
						context = [#l2_protocol{source_mac=S_MAC,dest_mac=D_MAC} | P_Tuple#packet_tuple.context]}),
		Counter#l2_counter{unicast_counter = Counter#l2_counter.unicast_counter + 1,
									   ip_counter = Counter#l2_counter.ip_counter + 1,
									   packet_counter = Counter#l2_counter.packet_counter + 1};
	_ ->
		Counter#l2_counter{unknown_counter = Counter#l2_counter.unknown_counter + 1,
									   packet_counter = Counter#l2_counter.packet_counter + 1}
	end;
do(_,_) ->
	undef.	


	